<template>
  <div class="device">
    <div class="device-header">
      <!-- 新增按钮 -->
      <el-button type="primary" @click="handleCreate">+ 新增设备</el-button>
      <!-- 搜索框 -->
      <!-- <el-form :inline="true">
        <el-form-item>
          <el-input size="small" v-model="searchForm.name" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="search">查询</el-button>
        </el-form-item>
      </el-form> -->
    </div>

    <!-- 设备数据表格 -->
    <div class="common-table">
      <el-table :data="tableData" stripe style="width: 100%" height="90%">
        <!-- 设备表格列 -->
        <!-- 根据设备的属性调整列 -->
        <el-table-column align="center" prop="deviceName" label="设备名称">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDetail(scope.row)">
              <div class="text-ellipsis-one">
                {{ scope.row.deviceName }}
              </div>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="deviceId" label="设备ID" width="350">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.deviceId" placement="top">
              <div class="text-ellipsis-one">{{ scope.row.deviceId }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="macAddress" label="设备MAC地址"> </el-table-column>
        <el-table-column align="center" prop="online" label="设备是否在线">
          <template slot-scope="scope">
            <span>{{ scope.row.isOnline ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="ipAddress" label="设备IP地址"> </el-table-column>
        <el-table-column align="center" prop="deviceStatus" label="设备状态">
          <template slot-scope="scope">
            <span>{{ deviceStatusType[scope.row.deviceStatus] }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="deviceType" label="设备类型">
          <template slot-scope="scope">
            <span>{{ deviceType[scope.row.deviceType] }}</span>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" align="left">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button class="danger-text" type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pager">
        <el-pagination layout="prev, pager, next" :total="total" @current-change="currentChange"> </el-pagination>
      </div>
    </div>
    <!-- 对话框 -->
    <el-dialog :title="modalType === 0 ? '新增设备' : '编辑设备'" :visible.sync="dialogVisible" width="40%" :before-close="closeDialog">
      <!-- 设备表单 -->
      <el-form :inline="false" :model="form" :rules="rules" ref="form" label-width="120px">
        <!-- 表单项 -->
        <el-form-item label="设备名称" prop="deviceName">
          <el-input placeholder="请输入设备名称" v-model="form.deviceName"></el-input>
        </el-form-item>

        <el-form-item label="设备ID" prop="deviceId">
          <el-input placeholder="请输入设备ID" v-model="form.deviceId"></el-input>
        </el-form-item>

        <el-form-item label="设备MAC地址" prop="macAddress">
          <el-input placeholder="请输入设备MAC地址" v-model="form.macAddress"></el-input>
        </el-form-item>

        <el-form-item label="设备是否在线" prop="isOnline">
          <el-switch v-model="form.isOnline" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>

        <el-form-item label="设备IP地址" prop="ipAddress">
          <el-input placeholder="请输入设备IP地址" v-model="form.ipAddress"></el-input>
        </el-form-item>
        <el-form-item label="设备状态" prop="deviceStatus">
          <el-select v-model="form.deviceStatus" placeholder="请选择设备状态" :style="{ width: '100%' }">
            <el-option label="正常" :value="0"></el-option>
            <el-option label="故障" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型" :style="{ width: '100%' }">
            <el-option label="类型A" :value="1"></el-option>
            <el-option label="类型B" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 确定和取消按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDeviceListApi, updateDeviceApi, addDeviceApi, deleteDeviceApi } from "@/api/deviceApi";

export default {
  data() {
    return {
      deviceStatusType: {
        0: "正常",
        1: "故障",
      },
      deviceType: {
        1: "类型A",
        2: "类型B",
      },
      // 设备表单数据
      form: {
        deviceName: "",
        deviceId: "",
        macAddress: "",
        isOnline: false,
        ipAddress: "",
        deviceType: "",
        deviceStatus: 0,
      },
      // 设备表单验证规则
      rules: {
        name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
        id: [{ required: true, message: "请输入设备ID", trigger: "blur" }],
        macAddress: [{ required: true, message: "请输入设备MAC地址", trigger: "blur" }],
        online: [{ required: true, message: "请输入设备是否在线", trigger: "blur" }],
        ipAddress: [{ required: true, message: "请输入设备IP地址", trigger: "blur" }],
        status: [{ required: true, message: "请输入设备状态", trigger: "blur" }],
        type: [{ required: true, message: "请输入设备类型", trigger: "blur" }],
      },
      // 设备对话框是否可见
      dialogVisible: false,
      // 设备数据列表
      tableData: [],
      // 设备表单类型: 新建(0) 或 编辑(1)
      modalType: 0,
      // 分页数据对象
      pageData: {
        page: 1,
        limit: 20,
      },
      // 分页总数
      total: 0,
      // 设备搜索表单
      searchForm: {
        name: "",
      },
    };
  },
  methods: {
    // 获取设备数据列表
    async getDeviceList() {
      const list = await getDeviceListApi();
      this.tableData = list;
      console.log(this.tableData);
      this.total = list.length;
    },
    // 设备表单提交
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.modalType === 0) {
            // 新增设备
            const res = await addDeviceApi({
              params: this.form,
              traceId: new Date().getTime().toString(),
            });
            if (!res) {
              this.$message.error("操作失败，请重试！");
            } else {
              this.$message.success("操作成功！");
              this.getDeviceList();
            }
          } else {
            // 编辑设备
            console.log(this.form);
            const res = await updateDeviceApi({
              params: this.form,
              traceId: new Date().getTime().toString(),
            });
            if (!res) {
              this.$message.error("操作失败，请重试！");
            } else {
              this.$message.success("操作成功！");
              this.getDeviceList();
            }
          }
          this.closeDialog();
        }
      });
    },
    // 关闭设备对话框
    closeDialog() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    // 编辑设备按钮
    handleEdit(device) {
      this.modalType = 1;
      this.openForm();
      this.form = JSON.parse(JSON.stringify(device));
    },
    // 删除设备按钮
    handleDelete(device) {
      this.$confirm("此操作将永久删除该设备, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteDeviceApi({
            params: [device.deviceId],
            traceId: new Date().getTime().toString(),
          });
          if (!res) {
            this.$message.error("删除失败，请重试！");
          } else {
            this.$message.success("删除成功！");
            this.getDeviceList();
          }
          this.getDeviceList();
        })
        .catch(() => {
          this.$message.close();
        });
    },
    // 设备详情按钮
    handleDetail(device) {
      this.$router.push({ path: "/devicedetail", query: { id: device.deviceId } });
    },
    // 新建设备按钮
    handleCreate() {
      this.form = {
        deviceName: "",
        deviceId: "",
        macAddress: "",
        isOnline: false,
        ipAddress: "",
        deviceStatus: 0,
        deviceType: 1,
      };
      this.modalType = 0;
      this.openForm();
    },
    // 打开设备表单
    openForm() {
      this.dialogVisible = true;
    },
    // 改变页码
    currentChange(val) {
      this.pageData.page = val;
      this.getDeviceList();
    },
    // 设备搜索
    search() {
      this.getDeviceList();
    },
  },
  mounted() {
    this.getDeviceList();
  },
};
</script>

<style lang="less" scoped>
@import "./DeviceManager.less";
</style>
